<template>
  <div class="course-resource">
    <div class="main-content">
      <h3>
        课程资源
        <span class="subtitle">互动问答板块包含所有学院课程的完整学习。</span>
      </h3>
      <nav class="secondary-nav">
        <router-link
          :to="{ name: 'CourseResource', params: { tab: '全部' } }"
          class="nav-item"
          :class="{ active: currentTab === '全部' }"
          exact
          @click="updateCurrentTab('全部')"
        >
          全部
        </router-link>
        <router-link
          :to="{ name: 'CourseResource', params: { tab: '视频' } }"
          class="nav-item"
          :class="{ active: currentTab === '视频' }"
          @click="updateCurrentTab('视频')"
        >
          视频
        </router-link>
        <router-link
          :to="{ name: 'CourseResource', params: { tab: '课件' } }"
          class="nav-item"
          :class="{ active: currentTab === '课件' }"
          @click="updateCurrentTab('课件')"
        >
          教学课件
        </router-link>
        <div class="search-container">
          <input
            type="text"
            placeholder="搜索课程资源"
            class="search"
            v-model="searchQuery"
            @keydown.enter="searchResources"
          />
          <img
            src="@/assets/search.png"
            alt="Search Icon"
            class="search-icon"
            @click="searchResources"
          />
        </div>
      </nav>
      <div class="content">
        <div
          v-for="(module,index) in filteredModules"
          :key="module.id"
          :ref="'module-' + module.id"
          class="module"
        >
          <div class="module-header" @click="handleModuleHeaderClick(module)">
            <button class="module-toggle">
              <span>第{{ index+1 }}章: {{ module.title }}</span>
              <img
                :src="
                  module.open
                    ? require('@/assets/close.png')
                    : require('@/assets/open.png')
                "
                alt="Toggle"
                class="toggle-icon"
              />
            </button>
          </div>
          <div v-if="module.open" class="module-body">
            <ul class="resource-list">
              <li
                v-for="(resource,index) in module.filteredResources"
                :key="resource.id"
                :class="{
                  checked:
                    getResourceCheckStatus(resource.id) === 1 &&
                    resource.type !== '测试' &&
                    resource.type !== '作业',
                  submitted:
                    (resource.type === '测试' || resource.type === '作业') &&
                    resource.submit === '已提交',
                }"
              >
                <div
                  class="module-header section-header"
                  @click="handleResourceClick(resource)"
                  v-if="resource.type !== '测试' && resource.type !== '作业'"
                >
                  <button class="module-toggle section-toggle">
                    <span
                      >第{{ index+1 }}节:
                      {{ resource.section_name }}</span
                    >
                    <img
                      :src="
                        module.open
                          ? require('@/assets/close.png')
                          : require('@/assets/open.png')
                      "
                      alt="Toggle"
                      class="toggle-icon"
                    />
                  </button>
                </div>
                <div
                  class="resource-details"
                  v-else-if="
                    resource.type === '测试' || resource.type === '作业'
                  "
                >
                  <router-link
                    :to="{
                      name: 'Assignments',
                      params: { unitId: resource.unit_id },
                    }"
                    class="resource-type"
                  >
                    {{ resource.type }}
                  </router-link>
                  <span> {{ resource.title }}</span>
                  <span class="resource-ceshi"
                    >截止时间： {{ resource.deadline }}</span
                  >
                  <span class="resource-score" v-if="resource.score">
                    得分:{{ resource.score }}
                  </span>
                  <span class="module-progress">
                    {{ resource.submit }}
                  </span>
                </div>
                <div v-if="resource.open" class="module-body resource-details">
                  <ul class="resource-list">
                    <li
                      v-for="allresource in resource.resources"
                      :key="allresource.id"
                      :class="{
                        checked:
                          getResourceCheckStatus(allresource.id) === 1 &&
                          resource.type !== '测试',
                        submitted:
                          resource.type === '测试' &&
                          resource.submit === '已提交',
                      }"
                      class="resource-details"
                    >
                      <router-link
                        :to="{
                          name: 'VideoPlayer',
                          params: { videoId: module.id },
                          query: { resourceId: allresource.id },
                        }"
                        class="resource-type"
                      >
                        {{ allresource.type }}
                      </router-link>
                      <span>{{ allresource.title }}</span>
                      <span class="module-progress">
                        <span
                          v-if="getResourceCheckStatus(allresource.id) === 1"
                          >✔</span
                        >
                      </span>
                    </li>
                  </ul>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
    <div class="sidebar">
      <div class="sidebar-item">
        <img src="./survey/插画.png" alt="" />
      </div>
      <div class="progress-section">
        <h3>
          学习进度
          <span>已完成 {{ completedModules }} 章/共 {{ totalModules }} 章</span>
        </h3>
        <div class="progress-bar">
          <div
            class="progress-bar-inner"
            :style="{ width: progressBarWidth }"
          ></div>
        </div>
        <span>{{ progressPercent }}%</span>
      </div>
      <div class="related-courses">
        <h3>所属课程</h3>
        <p>游戏策划</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "CourseResource",
  props: {
    unitId: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      tabs: ["全部", "视频", "课件"],
      currentTab: "全部",
      searchQuery: "",
      searchTerm: "",
      modules: [],
      modeles2: [],
      modeles3: [],
      currentModule: null,
    };
  },
  computed: {
    filteredModules() {
      module.filteredResources = []; // 确保每个模块都有 filteredResources
      let modules = this.modules.map((module) => ({
        ...module,
        filteredResources: module.resources
          .map((section) => {
            const filteredResources = section.resources.filter((resource) => {
              const matchesTab =
                this.currentTab === "全部" ||
                resource.type.toLowerCase() === this.currentTab.toLowerCase();
              const matchesSearch =
                !this.searchTerm ||
                resource.title
                  .toLowerCase()
                  .includes(this.searchTerm.toLowerCase()) ||
                section.section_name
                  .toLowerCase()
                  .includes(this.searchTerm.toLowerCase()) ||
                module.title
                  .toLowerCase()
                  .includes(this.searchTerm.toLowerCase());
              return matchesTab && matchesSearch;
            });

            return {
              section_name: section.section_name,
              section_order: section.section_order,
              resources: filteredResources,
            };
          })
          .filter((section) => section.resources.length > 0),
      }));
      if (this.currentTab === "全部") {
        modules.forEach((module) => {
          module.filteredResources = module.filteredResources || [];

          this.modeles2.forEach((mod2) => {
            if (
              module.id === mod2.unit_id &&
              mod2.name.toLowerCase().includes(this.searchTerm.toLowerCase())
            ) {
              module.filteredResources.push({
                id: mod2.unit_id,
                type: mod2.type === "homework" ? "作业" : "测试", // 根据类型设置
                submit: mod2.submit,
                title: mod2.name,
                submissionTime: mod2.submissionTime,
                deadline: mod2.deadline,
                score: mod2.score,
              });
            }
          });
        });
      }

      return modules.filter((module) => module.filteredResources.length > 0);
    },
    completedModules() {
      return this.modules.filter((module) => {
        const allResourcesChecked = module.resources
          .flatMap((section) => section.resources)
          .filter(
            (resource) => resource.type !== "作业" && resource.type !== "测试"
          )
          .every((resource) =>
            this.modeles3.some(
              (mod3) => mod3.resourceId === resource.id && mod3.check >= 1
            )
          );

        // 检查所有测试资源的提交状态是否为“已提交”
        const allTestsSubmitted = this.modeles2
          .filter((mod2) => mod2.unit_id === module.id)
          .every((mod2) => mod2.submit === "已提交");

        return allResourcesChecked && allTestsSubmitted;
      }).length;
    },
    totalModules() {
      return this.modules.length;
    },
    progressBarWidth() {
      return this.totalModules
        ? `${(this.completedModules / this.totalModules) * 100}%`
        : "0%";
    },
    progressPercent() {
      if (this.totalModules > 0) {
        return Math.round((this.completedModules / this.totalModules) * 100);
      } else {
        return 0;
      }
    },
  },
  methods: {
    async fetchModules() {
      try {
        const response = await fetch(
          `http://8.138.12.59:1999/semesters/showunits?semester_id=${this.semester_id}`,
          {
            method: "GET",
          }
        );

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        this.modules = data.data.map((unit) => ({
          id: unit.unit_id,
          title: unit.unit_title,
          resources: unit.sections.map((section) => ({
            section_name: section.section_name,
            section_order: section.section_order,
            resources: section.unitResources.map((resource) => ({
              id: resource.resource_id,
              type: this.getResourceType(resource.resource_type),
              order: resource.resource_order,
              title: resource.resource_title,
            })),
          })),
        }));

        // 将数据存储到 localStorage 中，并存储当前的时间戳
        localStorage.setItem("courseModules", JSON.stringify(this.modules));

        // 调用 fetchModeles3 获取 modeles3 数据
        for (const module of this.modules) {
          await this.fetchModeles3(module.id);
        }
      } catch (error) {
        console.error("Error fetching modules:", error);
      }
    },

    async fetchModeles2() {
      try {
        const response = await fetch(
          `http://8.138.12.59:1999/assignments?semester_id=${this.semester_id}&&user_id=${this.user_id}`,
          {
            method: "GET",
          }
        );
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        this.modeles2 = data.data.flatMap((unit) => {
          const homeworks = unit.homework_list.map((homework) => ({
            id: homework.id,
            unit_id: unit.unit_id,
            name: homework.name,
            deadline: homework.deadline,
            score: homework.score,
            submit: homework.submit,
            type: "homework", // 添加类型标识
          }));

          const tests = unit.stu_test_list.map((test) => ({
            id: test.unit_test_id, // 使用测试的ID
            unit_id: unit.unit_id,
            name: test.title,
            deadline: test.end_time,
            score: test.test_score,
            submit: test.status, // 根据需要调整
            type: "test", // 添加类型标识
          }));

          return [...homeworks, ...tests]; // 合并两个数组
        });

        localStorage.setItem("modeles2", JSON.stringify(this.modeles2));
      } catch (error) {
        console.error("Error fetching modeles2:", error);
      }
    },
    async fetchModeles3(unitId) {
      try {
        const response = await fetch(
          `http://8.138.12.59:1999/resources/checkResource?user_id=${this.user_id}&&unit_id=${unitId}`,
          {
            method: "GET",
          }
        );
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        const newData = data.data.map((che) => ({
          resourceId: che.resourceId,
          check: che.check,
        }));

        // 过滤掉旧的相同 unit_id 的数据
        this.modeles3 = this.modeles3.filter((mod3) => mod3.unit_id !== unitId);

        // 添加新的数据
        this.modeles3 = [
          ...this.modeles3,
          ...newData.map((item) => ({ ...item, unit_id: unitId })),
        ];

        // 存储到本地存储
        localStorage.setItem("modeles3", JSON.stringify(this.modeles3));
        this.updateModuleResources(unitId);
      } catch (error) {
        console.error("Error fetching modeles3:", error);
      }
    },
    getResourceType(resourceType) {
      switch (resourceType) {
        case "video":
          return "视频";
        case "ppt":
          return "课件";
        default:
          return resourceType;
      }
    },
    updateCurrentTab(tab) {
      this.currentTab = tab;
      this.searchTerm = "";
      this.collapseAllModules();
    },
    searchResources() {
      this.searchTerm = this.searchQuery.trim().toLowerCase();
      if (this.searchTerm === "") {
        this.collapseAllModules();
      } else {
        this.expandSearchResults();
      }
    },
    handleModuleHeaderClick(module) {
      this.currentModule = module;
      module.open = !module.open;
      this.$forceUpdate();
    },
    handleResourceClick(resource) {
      resource.open = !resource.open;
      this.$forceUpdate();
    },
    collapseAllModules() {
      this.modules.forEach((module) => {
        module.open = false;
        if (module.filteredResources) {
          module.filteredResources.forEach((resource) => {
            resource.open = false;
          });
        }
      });
    },
    expandSearchResults() {
      this.filteredModules.forEach((module) => {
        module.open = true;
        if (module.filteredResources) {
          module.filteredResources.forEach((resource) => {
            resource.open = true;
          });
        }
      });
    },
    getResourceCheckStatus(resourceId) {
      const resource = this.modeles3.find(
        (mod3) => mod3.resourceId === resourceId
      );
      if (resource && resource.check >= 1) return 1;
      return 0;
    },
    updateModuleResources(unitId) {
      const module = this.modules.find((mod) => mod.id === unitId);
      if (module) {
        module.resources.forEach((resource) => {
          const resourceStatus = this.modeles3.find(
            (mod3) => mod3.resourceId === resource.id
          );
          if (resourceStatus) {
            if (resourceStatus.check >= 1) {
              resource.check = 1;
            } else resource.check = 0;
          }
        });
        // 将模块状态存储到 localStorage 中
        localStorage.setItem("modules", JSON.stringify(this.modules));

        this.$forceUpdate();
      }
    },
    autoUpdate() {
      this.fetchModules();
      this.fetchModeles2();
    },
  },
  created() {
    this.user_id = localStorage.getItem("userid");
    this.semester_id = localStorage.getItem("semester_id");

    // 初始数据获取
    this.fetchModules();
    this.fetchModeles2();

    // 设置定时器,更新一次数据
    setInterval(() => {
      this.autoUpdate();
    }, 6 * 60 * 60 * 1000);
  },
  mounted() {
    if (!this.modeles2.length) {
      this.fetchModeles2();
    }
    if (!this.modules.length) {
      this.fetchModules();
    }
  },
  beforeUnmount() {
    localStorage.removeItem("courseModules");
    localStorage.removeItem("modeles2");
    localStorage.removeItem("modeles3");
  },
};
</script>

<style scoped>
.course-resource {
  display: flex;
  margin: 0px 0px 50px;
  padding: 20px 100px;
  background-color: #f9f9f9;
}

.main-content {
  flex: 3;
  padding: 20px;
  background-color: #ffffff;
  margin: 0px 40px 0px 20px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  text-align: left;
}

h3 {
  margin: 0px 0px 20px 0px;
  font-size: 32px;
}

.subtitle {
  font-size: 12px;
  color: #888;
  margin-left: 20px;
  margin-bottom: 20px;
}

.secondary-nav {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.nav-item {
  width: auto;
  padding: 10px 15px;
  color: #000;
  text-decoration: none;
  font-weight: bold;
  transition: color 0.3s, border-bottom 0.3s;
}

.nav-item.active,
.nav-item:hover {
  color: #3b96ff;
  border-bottom: 2px solid #3b96ff;
}

.search-container {
  display: flex;
  align-items: center;
  margin-left: auto;
  margin-right: 70px;
  padding: 5px 10px;
  border: 1px solid #2a82e4;
  border-radius: 25px;
  background-color: #fff;
}

.search {
  border: none;
  outline: none;
  padding: 5px;
  border-radius: 25px;
  flex: 1;
  margin-right: 10px;
}

.search-icon {
  width: 20px;
  height: 20px;
  cursor: pointer;
}

.content {
  margin-top: 20px;
}

.module {
  margin-bottom: 20px;
}

.module-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f1f4f9;
  padding: 10px;
  border-radius: 4px;
  cursor: pointer;
}

.section-header {
  background: #f1f4f9ae;
}

.module-toggle {
  background: none;
  border: none;
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  text-align: left;
  color: #2a82e4;
}

.section-toggle {
  color: #000;
}

.module-toggle span {
  font-weight: bold;
}

.toggle-icon {
  display: inline-block;
  transition: transform 0.3s;
}

.toggle-icon.flipped {
  transform: rotate(180deg);
}

.module-body {
  padding: 10px;
  border: 1px solid #e0e0e0;
  border-top: none;
  border-radius: 0 0 4px 4px;
}

.resource-list {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.resource-list li {
  padding: 10px 0;
}

.sidebar h3 {
  margin: 0px 0px 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sidebar h3 .left-content {
  flex: 1;
}

.sidebar h3 span {
  font-size: 10px;
  color: grey;
}

.sidebar-item {
  width: 100%; /* 使每个条目占满整个宽度 */
  box-sizing: border-box; /* 确保边框和填充不会增加宽度 */
  padding: 10px; /* 可以根据需要调整内边距 */
}

.sidebar img {
  max-width: 100%; /* 图片最大宽度为父元素宽度 */
  height: auto; /* 自动调整高度以保持比例 */
}

.sidebar {
  flex: 1;
  background-color: transparent;
  text-align: left;
}

.progress-section,
.related-courses {
  margin-bottom: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  padding: 15px;
}

.progress-section h3,
.related-courses h3 {
  font-size: 18px;
  margin-bottom: 10px;
}

.related-courses p {
  margin: 0;
  color: #3b96ff;
  font-size: 10px;
  cursor: pointer;
}

.related-courses ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.related-courses li {
  margin: 5px 0;
  color: #000;
  cursor: pointer;
}

.progress-bar {
  width: 100%;
  background-color: #e0e0e0;
  border-radius: 5px;
  overflow: hidden;
  margin: 10px 0px;
}

.progress-bar-inner {
  height: 20px;
  background-color: #3b96ff;
  width: 0;
  border-radius: 5px;
  transition: width 0.3s;
}

.resource-details > :nth-child(-n + 2) {
  padding: 0 12px;
}

.resource-ceshi {
  padding: 0 20px;
  font-size: 10px;
}

.resource-list li.checked .resource-type,
.resource-list li.checked span,
.resource-list li.checked .module-progress,
.resource-list li.submitted .resource-type,
.resource-list li.submitted span,
.resource-list li.submitted .module-progress {
  color: green;
}

.resource-list li.submitted .resource-details .resource-score {
  color: red;
}

.resource-type {
  text-decoration: none;
  color: #3b96ff;
}

.module-progress {
  font-size: 12px;
  color: #888;
  float: right;
}
</style>
